#include "ParserMTL.h"

#include "Error.h"
#include <iostream>
#include "UtilFile.h"

using namespace prog3d;
using namespace fileIO;
using namespace std;

ParserMTL::ParserMTL(string nom) : Parser(nom,0) {
  if (isOk()) {
    setCommentLine("#");
    cout << "loading material... " << filename() << endl;
    skipToken();
  }
}

ParserMTL::~ParserMTL() {
  if (isOk()) {
    cout << filename() << " done" << endl;
  }
}


Color ParserMTL::readColor() {
  Color res;
  for(int k=0;k<3;k++) {
    res.set(k,readNumber());
  }
  return res;
}

void ParserMTL::load(BaseMaterial *m) {
  m->path(UtilFile::getPath(lexer().filename()));
  Material *courant=NULL;
  while (token()!=FIN) {
    if (sToken()=="#") {
        lireLigne();
    } else
    if (sToken()=="newmtl") {
      skipToken();
      if (m->material(sToken())==NULL) {
        courant=new Material();
        courant->name(sToken());
        m->add(sToken(),courant);
 //       cout << "adding material : " << "\"" << sToken() << "\"" << endl;
      }
      else courant=m->material(sToken());
      skipToken();
    } else
    if (sToken()=="map_kd") {
      skipMot();
      cout << sToken() << endl;
      if (UtilFile::exist(UtilFile::getPath(filename())+sToken())) {
        Texture *t=m->texture(sToken());
        courant->mapDiffuse(t);
      }
      else
        cout << "Texture " << sToken() << " missing..." << endl;
    } else
    if (sToken()=="ka") {
        skipToken();
        courant->ambient(readColor());
    } else
    if (sToken()=="kd") {
        skipToken();
        courant->diffuse(readColor());
    } else
    if (sToken()=="ks") {
        skipToken();
        courant->specular(readColor());
    } else
    if (sToken()=="ns") {
        skipToken();
        courant->shininess(readNumber());
    } else
      skipToken();
  }
}


